#import "SearchItemView.h"

@implementation SearchItemView
@synthesize flag;
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}

- (void)awakeFromNib{
    
    self.chooseArr = [NSMutableArray arrayWithCapacity:0];
    self.buttonArr = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i<6; i++) {
        UIButton *itemBut = (UIButton *)[self viewWithTag:i+1];
        [_buttonArr addObject:itemBut];
    }
    
    _searchTextField.delegate = self;
}

- (void)setItemArr:(NSArray *)itemArr{
    
    if (_itemArr!=itemArr) {
        _itemArr = itemArr;
        [_chooseArr removeAllObjects];
        for (int i = 0; i<itemArr.count; i++) {
            UIButton *but = _buttonArr[i];
            [but setBackgroundImage:[UIImage imageNamed:@"tip"] forState:0];
            [but setTitle:itemArr[i] forState:0];
        }
    }
}


- (IBAction)clickOnBut:(UIButton *)sender {
    NSLog(@"flag==%d",self.flag);
    
    int butTag = sender.tag;
    
    NSLog(@"选中==%i",butTag);
    
    int a = 0;
    if (butTag>0&&butTag<=3) {
        a=0;
    }
    else if(butTag>3&&butTag<=6){
        a=3;
    }
    else{
        a=6;
    }
    
    if ([_chooseArr containsObject:sender]) {
        [_chooseArr removeObject:sender];
        [sender setBackgroundImage:[UIImage imageNamed:@"tip"] forState:0];
    }
    else{
        for (int i = a; i<a+3; i++ ) {
            UIButton *but = _buttonArr[i];
            if (but==sender) {
                [sender setBackgroundImage:[UIImage imageNamed:@"jb_focus"] forState:0];
                [_chooseArr addObject:sender];
            }
            else{
                if ([_chooseArr containsObject:but]) {
                    [_chooseArr removeObject:but];
                    [but setBackgroundImage:[UIImage imageNamed:@"tip"] forState:0];
                }
                
            }
        }
        
    }

}

- (IBAction)cancleAction:(UIButton *)sender {
    
    [_searchTextField resignFirstResponder];
    [self.superview removeFromSuperview];
    
}
- (IBAction)conformAction:(UIButton *)sender {
    
    [_searchTextField resignFirstResponder];
    if ([self.delegate respondsToSelector:@selector(searchItemDidSelect:AndSearchText:)]) {
        
        NSLog(@"高级搜素_chooseArr==%@",_chooseArr);
        
        [self.delegate searchItemDidSelect:_chooseArr AndSearchText:_searchTextField.text];
    }
    [self.superview removeFromSuperview];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    
    if (textField.text.length>0) {
        [self conformAction:nil];
    }
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [_searchTextField resignFirstResponder];
}


@end
